// created by noellynch
// May 14, 2011

package com.gruntdb.engines.indexedjson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

import com.gruntdb.core.GruntDataStore;
import com.gruntdb.objects.GruntDBFile;
import com.gruntdb.objects.GruntDBFileSeek;
import com.gruntdb.objects.SizedOffset;

public class IndexedJSONSegmentFile {
	private		int					mi_index;
	private		long				ml_lowerIndex;
	private		long				ml_upperIndex;
	
	private		GruntDBFile			mcl_file;
	private		GruntDBFileSeek		mcl_addSeek;
	
	private		IndexedJSONStorageEngine		mcl_dataStore;
	
	private		SizedOffset			mcl_addResult = new SizedOffset();
	
	public	IndexedJSONSegmentFile(IndexedJSONStorageEngine cl_store, int i_index) {
		super();
		mi_index = i_index;
		mcl_dataStore = cl_store;
	}
	
	protected	void	initialiseFile() {
		try {
			mcl_file = new GruntDBFile(new File(mcl_dataStore.getLocation(), mi_index + "_" + mcl_dataStore.getFileReferenceName() + ".segment"));
			mcl_addSeek = mcl_file.getASeek();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public long getLowerIndex() {
		return ml_lowerIndex;
	}

	public void setLowerIndex(long mlLowerIndex) {
		ml_lowerIndex = mlLowerIndex;
	}

	public long getUpperIndex() {
		return ml_upperIndex;
	}

	public void setUpperIndex(long mlUpperIndex) {
		ml_upperIndex = mlUpperIndex;
	}
	
	protected	SizedOffset	saveValue(String str_value) {
		try {
			mcl_file.writeBytes(str_value);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		mcl_addResult.setOffset(mcl_addSeek.getCurrentSeek());
		mcl_addResult.setSize((str_value.length() << 1));
		
		// inc seek with new data
		mcl_addSeek.offset(mcl_addResult.getSize());
		
		return mcl_addResult;
	}
	
	public	int		getFileIndex() {
		return mi_index;
	}
	
	
}
